#include "UDPDatagram.h"
#include <string.h>
#include <iostream>

using namespace std;

UDPDatagram::UDPDatagram(const char *host, unsigned short port)
{
	/* get socket */
	sock_error = false;
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if(sock == -1) {
		cout << "Socket error" << endl;
		sock_error = true;
		return;
	}

	/* get server */
	struct addrinfo *result;
	addr_error = false;
	addr_error = getaddrinfo(host, NULL, NULL, &result);
	if(addr_error) {
		cout << "Address error" << endl;
		return;
	}

	server = *((struct sockaddr_in *)result->ai_addr);
	server.sin_port = htons(port);
	freeaddrinfo(result);
}

UDPDatagram::~UDPDatagram()
{
	close(sock);
}

int UDPDatagram::sendData(const char *data)
{
	if(sock_error || addr_error)
		return 1;

	int ret = sendto(sock, data, strlen(data), 0, (struct sockaddr *)&server ,sizeof(server));
	if(ret == -1) {
		cout << "sendto failed" << endl;
		return 1;
	}

	return 0;
}
